import axios from "axios";
import {message} from "antd";
import {router} from "@/routes/index.jsx";
import {AuthUtil} from "@/utils/auth.js";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const http = axios.create({
  // headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
  baseURL: 'http://geek.itheima.net/v1_0',
  timeout: 5000
})

// 添加请求拦截器
http.interceptors.request.use((config) => {
  // if not login add token
  const token = AuthUtil.getToken()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// 添加响应拦截器

http.interceptors.response.use(
  response => {
    const code = response.data.code || 200;
    console.log(response)

    if (code === 403) {
      message.error("你没有权限访问此接口", 2)
      return Promise.reject("无权访问接口")
    } else if (code === 401) {
      message.error("用户状态失效，请重新登录", 2)
      AuthUtil.removeToken()
      router.navigate('/login')
      return Promise.reject(response);
    } else {
      return Promise.resolve(response)
    }

  },
  error => {
    console.log('err' + error)
    let {msg} = error;
    if (msg === "Network Error") {
      msg = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      msg = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      msg = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    message.error(msg, 2)
    return Promise.reject(error)
  }
)


export {http}
